
// funcion para verificar que el archivo seleccionado con elemento input:file sea una imágen
// devuelve la ruta de la imagen o la información de la imagen si hubiera o nulo
// se requiere que el select tenga evento onchange y una imágen en blanco para vista previa
	//		<input type="file" onchange='document.getElementById("preview").src=getPath(this);' ... />
	// 		<img src='img/blank.gif' id='preview' ... />
	//	usando cake form helper
	//		echo $form->input('imagen',array(
	//	 		'label'=>'Imágen',
	//	 		'type'=>'file',
	//	 		'class'=>'subir_imagen',
	//			'onchange'=>'document.getElementById("preview").src=getPath(this);'
	//	 		'after'=>'<div align="center">'.$html->image('blank.gif',array('alt'=>'vista previa','width'=>'100','height'=>'80','id'=>'preview')).'</div>'))
function getPath(input){
	//verificando la extension
	ext=input.value.split('.')[input.value.split('.').length-1];
	if(ext=='jpg'||ext=='gif'||ext=='png'||ext=='jpeg'){
		if(input.files && input.files[0]){
			return input.files[0].getAsDataURL();
		}
		return input.value || "nada seleccionado";	
	}
	else{
		alert('seleccione una imagen');
		input.value="";
		return blank_image;
	}
}

function repeat(str, c){
    var r = '';
    for (var i = 0; i < c; i++){
        r += str;
    }
    return r;
}

function StrToDate(str, format){
    format = typeof(format) != 'undefined' ? format : 'dd/mm/yyyy';
    var d = new Date();
    var c = '/';
    if (format.indexOf('/')>=0)
        c = '/';
    else
        c = '-';
    var formatParts = format.split(c);
    var dateParts = str.split(c);
    var day;
    var month;
    var year;
    if (formatParts.length >= 3){
        for(var i = 0; i < formatParts.length; i++){
            if (formatParts[i].charAt(0)=='d'){
                day = parseInt(dateParts[i]);
            }
            else if (formatParts[i].charAt(0)=='m'){
                month = parseInt(dateParts[i]);
            }
            else if(formatParts[i].charAt(0)=='y'){
                year = parseInt(dateParts[i]);
            }
        }
        d = new Date(year, month, day);
    }
    return d;
}

function init_script_addedit_only(){
	/*
	//TECLA DE MÉTODO ABREVIADO CTRL+G = GUARDAR
	$(document).bind('keydown', 'Ctrl+g', function(){
		if (confirm('Seguro desea guardar los datos?'))
			$("form").submit(); 
		return false;  
	});
	*/
	
	//AGREGANDO BOTON DE SELECCIÓN DE FECHAS PARA CONTROLES DATE DE CAKEPHP (CON 3 SELECTS)
	$('div.date').append('<input class="datepicker" type="hidden"/>');
	if(jQuery().datepicker) {	
		$('.dateselector').datepicker({
			dateFormat: 'dd/mm/yy',
			buttonImage: _WEB_ROOT+'img/calendar.png',
			buttonImageOnly: true,
			duration: '',
			showOn: 'button',
			changeMonth:false,
			changeYear:false					
		});	
		$('.datepicker').datepicker({
			dateFormat: 'yy-mm-dd',
			buttonImage: _WEB_ROOT+'img/calendar.png',
			buttonImageOnly: true,
			duration: '',
			showOn: 'button',
			changeMonth:true,
			changeYear:true,
			dayNamesMin:['Dom','Lun','Mar','Mi&eacute;','Jue','Vie','Sab'],
			monthNamesShort:['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Set','Oct','Nov','Dic'],
			onSelect: function(sel_date) {
				var newDate = sel_date.split('-');
				
				$(this).siblings('select').each(function(){
					id = $(this).attr('id');
					if (id.substring(id.length-3, id.length)=='Day') $(this).val(newDate[2]);
					else if (id.substring(id.length-5, id.length)=='Month') $(this).val(newDate[1]);
					else if (id.substring(id.length-4, id.length)=='Year') $(this).val(newDate[0]);
				});
			},
			beforeShow: function() {
				var year = '';
				var month = '';
				var day = '';
				var id = '';
				$(this).siblings('select').each(function() {
					id = $(this).attr('id');
					if (id.substring(id.length-3, id.length)=='Day') day = $(this).val();
					else if (id.substring(id.length-5, id.length)=='Month') month = $(this).val();
					else if (id.substring(id.length-4, id.length)=='Year') year = $(this).val();
				});
				$(this).val(year+'-'+month+'-'+day);
				return {};
			}
		});
		$('#ui-datepicker-div').css('font-size','0.8em');
	} else {
		//jQuery plugin DOES NOT exist
	}

	//AGREGANDO BOTON DE SELECCIÓN DE FECHAS PARA CONTROLES DATE DE CAKEPHP (CON 1 INPUT TEXT)
	$('div.simpleDate').append('<input class="datepicker" type="hidden"/>');
	if(jQuery().datepicker) {
		$(':text.dateselector')
		.bind('focusout.checkDateFormat',function(){
			fecha = this.value.trim();
			if(fecha){
				if(/(^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)[0-9]{2}$|(00\/00\/0000))/.test(fecha)){
					return true;
				} else if(/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])$/.test(fecha)) {
					//permite utilizar formato de fecha:    dd/mm
					this.value = fecha + '/' + _WORK_YEAR;
				} else {
					this.value = '00/00/0000';
				}
			} else {
				this.value = '00/00/0000';
			}
		})
		.trigger('focusout')
		.datepicker({
				dateFormat: 'dd/mm/yy',
				buttonImage: _WEB_ROOT+'img/calendar.png',
				buttonImageOnly: true,
				duration: '',
				showOn: 'button',
				changeMonth:true,
				changeYear:true
		});
		$('.datesession').datepicker({
				dateFormat: 'DD, d MM yy',
				maxDate: '+0D'
		});

		$('.datepicker').datepicker({
				dateFormat: 'dd/mm/yy',
				buttonImage: _WEB_ROOT+'img/calendar.png',
				buttonImageOnly: true,
				duration: '',
				showOn: 'button',
				changeMonth:true,
				changeYear:true,
				dayNamesMin:['Dom','Lun','Mar','Mi&eacute;','Jue','Vie','Sab'],
				monthNamesShort:['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Set','Oct','Nov','Dic'],
				onSelect: function(sel_date) {
						$(this).siblings('input').val(sel_date);
						$(this).siblings('input').change();
				},
				beforeShow: function() {
						$(this).val($(this).siblings('input').val());
						return {};
				}
		});
		$('#ui-datepicker-div').css('font-size','0.8em');
	}
	
	
	//extendiendo la funcionalidad de los selectores de fecha que contengan atributo minDate, maxDate
	$(':text.hasDatepicker')
    .filter('[maxdate]').each(function(){
        $this = $(this);
        x = $('<input>').datepicker({
            defaultDate: $this.datepicker('getDate')
        });
        strMaxDate = $this.attr('maxdate');
        if(strMaxDate.indexOf(',')>-1){
			//verificando si el texto tiene la forma de fecha yy,mm,dd
            strMaxDate = strMaxDate.split(',');
			if(strMaxDate[0] === 'now'){
				strMaxDate[0] = _WORK_YEAR;
			}
			if(strMaxDate[1] === 'now'){
				strMaxDate[1] = _WORK_MONTH-1;
			}
			if(strMaxDate[2] === 'now'){
				strMaxDate[2] = _WORK_DATE.substr(0,2);
			}
		
            strMaxDate = new Date(strMaxDate[0], strMaxDate[1]-1, strMaxDate[2]);
        }
        maxDate = x.datepicker('setDate', strMaxDate).datepicker('getDate');
        
        $this.datepicker('option','maxDate', maxDate);
    }).end()
    .filter('[mindate]').each(function(){
        $this = $(this);
        x = $('<input>').datepicker({
            defaultDate: $this.datepicker('getDate')
        });
        strMindate = $this.attr('mindate');
        if(strMindate.indexOf(',')>-1){
            strMindate = strMindate.split(',');
			if(strMindate[0] === 'now'){
				strMindate[0] = _WORK_YEAR;
			}
			if(strMindate[1] === 'now'){
				strMindate[1] = _WORK_MONTH-1;
			}
			if(strMindate[2] === 'now'){
				strMindate[2] = _WORK_DATE.substr(0,2);
			}
            strMindate = new Date(strMindate[0], strMindate[1]-1, strMindate[2]);
        }
        minDate = x.datepicker('setDate', strMindate).datepicker('getDate');
        
        $this.datepicker('option','minDate', minDate);
    }).end()
    .filter('[mindate],[maxdate]').bind('change.validarMinMaxDate', function(){
        $this = $(this);
        inputDate = $this.datepicker('getDate');
        maxDate = $this.datepicker('option','maxDate');
        minDate = $this.datepicker('option','minDate');
            
        function isValidDate(){
            
            state = true;
            if($this.datepicker('option','minDate')){
                state = state && (inputDate >= minDate);
            }
            if($this.datepicker('option','maxDate')){
                state = state && (inputDate <= maxDate);
            }
            return state;
        }
        
        if(!isValidDate()){
            minDate = minDate?minDate.to_string('dd/mm/yy'):'...';
            maxDate = maxDate?maxDate.to_string('dd/mm/yy'):'...';
            alerta('La fecha seleccionada es incorrecta debe estar entre <br>'+ minDate.bold() +' y '+ maxDate.bold());
            $this.datepicker('setDate', new Date());
        }
    });
}

$(function() {
	init_script_addedit_only();
	build_menu();
});